package com.billow.net.rtmp
{
	import flash.net.ObjectEncoding;
	import flash.utils.ByteArray;
	import flash.utils.Endian;

	internal class RtmpPacket
	{
		public var rtmpChannel:uint = 0x03;
		public var rtmpBodyType:uint = 0;
		public var rtmpBodySize:uint = 0;
		public var streamTimeStamp:uint = 0;
		public var streamChannel:uint = 0;
		public var chunkSize:uint = 0;
		public var remaining:uint = 0;
		
		private var _objectEncoding:uint;
		private var _rtmpBody:ByteArray;
		
		public function RtmpPacket(encoding:uint = ObjectEncoding.AMF0)
		{
			_objectEncoding = encoding;
			_rtmpBody = new ByteArray();
			_rtmpBody.objectEncoding = ObjectEncoding.AMF0;
		}
		
		public function get objectEncoding():uint {return _objectEncoding;}
		public function set objectEncoding(value:uint):void {_objectEncoding = value;}
		
		public function get rtmpBody():ByteArray {return _rtmpBody;}
		
		public function clear():void {_rtmpBody.clear();}
		
		public function readObject():Object
		{
			var obj:Object = null;
			
			if(_rtmpBody[_rtmpBody.position] == 0x11)
			{
				if(_objectEncoding == ObjectEncoding.AMF3)
				{
					_rtmpBody.readByte();
					_rtmpBody.objectEncoding = ObjectEncoding.AMF3;
					obj = _rtmpBody.readObject();
					_rtmpBody.objectEncoding = ObjectEncoding.AMF0;
				}
			}
			else
			{
				obj = _rtmpBody.readObject();
			}
			
			return obj;
		}
		
		public function writeObject(value:Object):void
		{
			if(value is uint || value is int || value is Number || value is String || value == null || value is Boolean)
			{
				_rtmpBody.writeObject(value);
			}
			else
			{
				if(_objectEncoding == ObjectEncoding.AMF3)
				{
					_rtmpBody.writeByte(0x11);
					_rtmpBody.objectEncoding = ObjectEncoding.AMF3;
					_rtmpBody.writeObject(value);
					_rtmpBody.objectEncoding = ObjectEncoding.AMF0;
				}
			}
		}
		
		
		
		public function clone():RtmpPacket
		{
			var result:RtmpPacket = new RtmpPacket(_objectEncoding);
			result.rtmpChannel = rtmpChannel;
			result.rtmpBody.writeBytes(_rtmpBody);
			result.rtmpBody.position = 0;
			result.rtmpBodyType = rtmpBodyType;
			result.rtmpBodySize = rtmpBodySize;
			result.streamTimeStamp = streamTimeStamp;
			result.streamChannel = streamChannel;
			result.chunkSize = 0;
			result.remaining = 0;
			
			return result;
		}
		
		public function toString():String
		{
			return 	"RtmpPacket rtmpChannel = " + rtmpChannel +
					", rtmpBodyType = " + rtmpBodyType +
					", rtmpBodySize = " + rtmpBodySize +
					", streamTimeStamp = " + streamTimeStamp +
					", streamChannel = " + streamChannel;
		}
	}
}